package com.zm.demo.drools;

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * @author z01140
 * @Package: com.zm.demo.drools
 * @Description:
 * @CreateDate 2023/7/6 11:53
 * @UpdateDate 2023/7/6 11:53
 */
@Configuration
public class DroolsConfiguration {

    final static String RULE_PATH = "rules/";
    @Bean
    public KieServices getKieServices(){
        return KieServices.get();
    }

    private Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        return resourcePatternResolver.getResources("classpath*:" + RULE_PATH + "**/*.*");
    }
    @Bean
    public KieFileSystem kieFileSystem() throws IOException {

        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        for (Resource ruleFile : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULE_PATH + ruleFile.getFilename(), "UTF-8"));
        }
        return kieFileSystem;
    }

    @Bean
    public KieContainer kieContainer() throws IOException {
        KieRepository kieRepository = getKieServices().getRepository();
        kieRepository.addKieModule(() -> kieRepository.getDefaultReleaseId());
        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        KieContainer kieContainer = getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
        return kieContainer;
    }

    @Bean
    public KieBase kieBase() throws IOException {
        return kieContainer().getKieBase();
    }
}
